package com.ztgf.shopping.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @description: 为解决集群环境下 TM 获取唯一的模块标识（appliction_name) 此处手动动态拼装
 * spring.application.name
 * <p>
 * 启动前 动态修改或 加载 全局配置属性
 * @author: chenyu.wang
 * @date: 2019-09-12 15:26
 */
@Slf4j
@Component
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private static final String PROPERTY_SOURCE_NAME = "defaultProperties";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment,
                                       SpringApplication application) {
        String applicationName = environment.getProperty("dubbo.application.name");
        if (StringUtils.isEmpty(applicationName)) {
//            System.out.println(".............dubbo.application.name is null");
            applicationName = "application";
        }
        Map<String, Object> map = new HashMap();
        map.put("spring.application.name", applicationName + getRandom());
        MapPropertySource target = (MapPropertySource) environment.getPropertySources().get(PROPERTY_SOURCE_NAME);
        if (target == null) {
            target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
        }
        environment.getPropertySources().addLast(target);

//        System.out.println(".............spring.application.name is:" + environment.getProperty("spring.application.name"));
    }

    private String getRandom() {
        String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM";
        Random random = new Random();
        StringBuffer sb = new StringBuffer("-");
        for (int i = 0; i < 6; ++i) {
            int number = random.nextInt(52);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


}